/** https://www.npmjs.com/package/git-work-record */

import GitWrokRecord from 'git-work-record';
import fs from 'fs';
import path from 'path';
import dayjs from 'dayjs';

function mkdirSync(dirname) {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    if (mkdirSync(path.dirname(dirname))) {
      fs.mkdirSync(dirname);
      return true;
    }
  }
}

async function genFileName() {
  const dir = path.resolve(
    process.cwd(),
    'report/' + dayjs().format('YYYY') + '/' + dayjs().format('MM')
  );
  await mkdirSync(dir);
  const fileName = dir + '/' + dayjs().format('DD') + '.md';
  return fileName;
}

const main = async () => {
  let logs = await GitWrokRecord({
    deep: 10,
    cwd: '/Users/yanggang.g.yang/workspace',
    /**别名 day，类似 git log 的 since 参数，用来查询特定时间范围的提交记录。具体的时间取值，
     * 格式：?days , ?weeks , ?years, 2016-11-25 , 传递数字会当做 ?days，如 --since=2 ，会当做 2days 查询近 2 天的数据。 */
    since: '1days',
  });
  logs = logs
    .filter((ele) => ele.project !== 'git-work-report')
    .filter((ele) => !ele.text.startsWith('Merge'))
    .map((ele) => ({
      ...ele,
      text: ele.text
        .replace(/feat/, '新增功能')
        .replace(/fix/, '优化')
        .replace(/docs/, '文档')
        .replace(/refactor/, '重构')
        .replace(/test/, '测试')
        .replace(/chore/, '构建')
        .replace(/style/, '样式'),
    }));
  const obj = {};
  logs.forEach((ele) => {
    if (!obj[ele.project]) {
      obj[ele.project] = [];
    }
    obj[ele.project].push(ele.text);
  });
  const fileName = await genFileName();
  let contentStr = '';
  Object.keys(obj).forEach((k) => {
    contentStr += '### ' + k + '\n';
    obj[k].forEach((v) => {
      contentStr += '- ' + v + '\n';
    });
    contentStr += '\n';
  });
  fs.writeFileSync(fileName, contentStr);
  console.log(contentStr);
};
main();
